/*
 * Copyright 2005-2010 the original author or authors.
 * 
 *      ruixun
 *
 * Project csmp
 */
package com.csmp.service.impl;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Projections;

import com.bs.bean.Role;
import com.csmp.service.AbstractRoleService;

/**
 * @author lizhiqiang
 * @version 2011-2-22
 * @since JDK 1.5
 */
public class RoleServiceImpl extends AbstractRoleService {

	protected void delObj(Role entity) {
		getHibernateTemplate().delete(entity);

	}

	protected Role loadObj(Serializable id) {
		return (Role) getHibernateTemplate().get(CLASS_NAME, id);
	}

	protected void saveObj(Role entity) {
	 getHibernateTemplate().saveOrUpdate(entity);
	}

	@SuppressWarnings("unchecked")
	protected List<Role> searchList(Role entity,int first,int max) {
		DetachedCriteria criteria = getCriteria();
		setContion(entity, criteria);
		List<Role> list = getHibernateTemplate().findByCriteria(criteria,first,max);
		return list;
	}

	private DetachedCriteria getCriteria() {
		return DetachedCriteria.forClass(CLASS_NAME);
	}
	
	@SuppressWarnings("unchecked")
	public int getCount(Role bean) {
		DetachedCriteria criteria=DetachedCriteria.forClass(CLASS_NAME);
		try {
			setContion(bean,criteria);
		} catch (Exception e) {
			e.printStackTrace();
		}
		criteria.setProjection(Projections.rowCount());
		List<Integer> list=getHibernateTemplate().findByCriteria(criteria);
		if(list == null || list.isEmpty()){
			return 0;
		}
		return list.get(0);
	}
	
	private void setContion(Role entity,DetachedCriteria criteria){
		
		if(StringUtils.isNotBlank(entity.getName())){
			criteria.add(Expression.like("name", "%"+entity.getName().trim()+"%"));
		}
		
		if(StringUtils.isNotBlank(entity.getCode())){
			criteria.add(Expression.like("code", "%"+entity.getCode().trim()+"%"));
		}
		
	}

	@SuppressWarnings("unchecked")
	public List<Object> search(String hql) {
		List<Object> list=getHibernateTemplate().find(hql);
		return list;
	}

}
